(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:AboutCtrl
     * @description
     * # AboutCtrl
     * Controller of the webApp
     {
      title:"发票商品标题",//模板设置显示内容
                        id:'invoice-invoice_items-name',表隐射名-主表字段名(假如该项是隐射子表这应为映射子表印射名)-要填入属性(假设字段是嵌套JSON对象可以加入链接)
                        ids:['name'],//为子表下 即第二个对象下的属性，可以迭代子孙对象  
                        values:{name:[]},具体要得到展示对象属性
                        value:"A2121312商品"
                        }
     */
    angular.module('webApp')
        .controller('PrintCtrl', PrintCtrl);

    PrintCtrl.$inject = ['$scope', 'dataService', '$timeout', '$location', 'helper', '$document', '$filter', '$rootScope','$compile'];


    function PrintCtrl($scope, dataService, $timeout, $location, helper, $document, $filter, $rootScope,$compile) {

        //打印列表初始方法
        $scope.listAction = function() {
            $scope.getprinterlist();
        }
        //模板
        $scope.templateAction = function() {
            $scope.chosedType = "xiaopao";
            $scope.store_id = $rootScope.store_id;
            $scope.type_id = $scope.tep_type = 2;
            $scope.pageSize = 10;
            $scope.getlist();
        }
        //获取打印配置
        $scope.getprinterlist = function() {
            dataService.printerGet({page_size:100}).then(function(result) {
                if (result.printers_list) {
                    var list = clone(result.printers_list);
                    _.map(list, function(data) {
                        if (data.store_ids) {
                            data.store_ids = data.store_ids.split(",");
                            data.ary = {};
                            _.map(data.store_ids, function(da, key) {
                                data.ary[da] = da;
                            });
                            console.error("$scope.printersList", data.ary[$scope.store_id]);
                        }
                    });
                    $scope.printersList = list;
                    console.error("$scope.printersList", $scope.printersList);
                }
            })
        }
        //修改store_ids字段
        $scope.saveStoreid = function(printer_id, type) {
            var data = {
                printer_id: printer_id,
                type: type,
                store_id: $scope.store_id,
            };

            dataService.printerUpstoreid(data).then(function(result) {
                if (result.printer_id) {
                    $scope.getprinterlist();
                } else {
                    helper.myAlert("error" + result.Msg);
                }
            })
        }
        //添加打印
        $scope.Addprinter = function() {
            var data = {
                word: "设备唯一识别id",
                device_name: "设备名称",
                printer_uuid: "打印机唯一识别id",
                printer_name: "打印机名称",
                store_id: $rootScope.store_id,
            };

            dataService.printerAdd(data).then(function(result) {

            })
        }
        //删除打印机
        $scope.Remprinter = function(id) {
            var data = {
                printer_id: id,
            };
            helper.myConfirm("确认删除吗？", function() {
                dataService.printerRemove(data).then(function(result) {
                    if (result.printer_id) {
                        $scope.getprinterlist();
                    } else {
                        helper.myAlert("error" + result.Msg);
                    }
                })
            });
        }
        //打印
        $scope.print = function() {
            var data = {
                "xiaopiao_type": "item",
                "order_id": "2550845953246535681",
                "printer_uuid": "DC:0D:30:28:77:72",
                "store_id": $rootScope.store_id,
            };
            dataService.printerGetpos(data).then(function(result) {
                if (result.printer_id) {
                    $scope.getprinterlist();
                } else {
                    helper.myAlert("error" + result.Msg);
                }
            })
        }
        //获取打印配置
        $scope.getlist = function() {
            if ($scope.chosedType == 'xiaopao') {
                $scope.tep_type = $scope.type_id = 2;
            }
            if ($scope.chosedType == 'express') {
                $scope.tep_type = $scope.type_id = 1;
            }
            dataService.printSellerGet({
                page_no: 1,
                page_size: $scope.pageSize,
                query: {
                    // 'type_id':type_id?type_id: $scope.type_id,
                    'tep_type': $scope.tep_type,
                    'store_id': $rootScope.store_id,
                },
            }).then(function(result) {
                var re = result.prints;
                $scope.oldPrints = re;
                $scope.tpMl = {};
                _.map(re, function(dd, kk) {
                    dd.default_printer = dd.default_printer ? JSON.parse(dd.default_printer) : {};
                    if (!$scope.tpMl) {
                        if (dd.shipping_corp) {
                            $scope.tpMl[dd.shipping_corp].push(dd);
                        }
                    }
                    if ($scope.tpMl[dd.shipping_corp]) {
                        $scope.tpMl[dd.shipping_corp].push(dd);
                    } else {
                        if (dd.shipping_corp) {
                            $scope.tpMl[dd.shipping_corp] = [];
                            $scope.tpMl[dd.shipping_corp].push(dd);
                        }
                    }
                });
                $timeout(function() {
                    $scope.getdfexpress();
                });
            })
        }
        //修改 
        $scope.delprint = function(item, printerlists, print_id) {
            _.map(printerlists, function(da, kk) {
                if (da == item) {
                    printerlists.splice(kk, 1);
                }
            });
            console.error("printerlists.length ", printerlists.length);
            if (printerlists.length <= 0) {
                printerlists = '';
            }
            var data = { print_id: print_id, default_printer: printerlists };
            $scope.saveprinter(data);
        }

        //修改默认打印机
        $scope.saveprinter = function(updata, type) {
            // console.log("updata",updata);
            if (type) {
                updata.default_printer = '';
            }
            // updata.default_printer = updata.default_printer ? updata.default_printer) : updata.default_printer;
            $scope.saveData(updata);

        }

        //设置快递公司
        $scope.SaveExpress = function(code, ky) {
            $timeout(function() {
                var tcode = 1;
                if ($scope.tpMl[code]) {
                    for (var i = 0; i < $scope.tpMl[code].length; i++) {
                        if ($scope.tpMl[code][i].value.subtype) {
                            tcode = 0;
                            break;
                        }
                    }
                }
                // console.log("eeeeeeeeeeeeeeeeeeeeeeeeeeee", $scope.tpMl[code], tcode);
                return tcode;
            }).then(function(isda) {
                // console.log("ddddddddddddddd", isda);
                _.map($scope.selectMailTpl, function(valu, key) {
                    if (key == ky) {
                        valu.value.cp_code = code;
                        if (isda) {
                            valu.value.subtype = 1;
                        }
                        delete valu.value.code;
                        $scope.upData(valu);
                    }
                });
            });
        }

        //设置默认模板
        $scope.NewcheckDefault = function(isvData, tpMlkey) {
            var isData = {
                "print_id": isvData.print_id,
                "default_template": 1,
            };
            if (isData.print_id) {
                //先修改之前默认的 
                $timeout(function() {
                    var data;
                    _.map($scope.tpMl[tpMlkey], function(a) {
                        if (a.default_template) {
                            data = a;
                            data.default_template = "";
                        }
                    });
                    return data;
                }).then(function(data) {
                    if (data) {
                        var ddata = { "print_id": data.print_id, "default_template": data.default_template };
                        if (data.default_express) {
                            if ($scope.dfExpress.shipping_corp == data.shipping_corp) {
                                ddata.default_express = 0;
                            }
                            isData.default_express = 1;
                        }
                        return dataService.printSellerUpdate(ddata).then(function(r) {
                            if (!r.Msg) {
                                $scope.saveData(isData);
                            } else {
                                helper.myAlert("error" + r.Msg);
                            }
                        });
                    } else {

                        $scope.saveData(isData);
                    }
                });
            }
        }

        //修改数据
        $scope.saveData = function(isvData, type) {
            if (isvData.content) {
                delete isvData.content;
            }
            console.log("isvData", isvData);
            if (isvData.default_printer) {
                isvData.default_printer = JSON.stringify(isvData.default_printer);
            }
            return dataService.printSellerUpdate(isvData).then(function(r) {
                if (!r.Msg) {
                    if (type) {
                        return r;
                    } else {
                        $scope.getlist();
                    }
                } else {
                    helper.myAlert("error" + r.Msg);
                }
            });
        }

        //创建修改打印模板初始化方法
        $scope.addAction = function() {
            $scope.tpid = $location.search().id;
            $scope.type_id = $location.search().type_id;
            console.log("tpid", $scope.tpid);
            if ($scope.tpid) {
                // dataService.printPubOne( $scope.tpid).then(function(r) {

                // });
            } else {

            }
        }

        //获取 默认快递公司
        $scope.getdfexpress = function() {
            dataService.printSellerGet({ query: { 'default_express': 1, store_id: $rootScope.store_id } }).then(function(r) {
                if (r.prints.length > 0) {
                    $scope.dfExpress = r.prints[0];
                }
            });
        }

        //设置默认快递公司
        $scope.ExpressDefault = function(code) {
            $timeout(function() {
                var is;
                //选把旧 的默认物流给修改成普通的
                if ($scope.dfExpress) {
                    for (var i = $scope.oldPrints.length - 1; i >= 0; i--) {
                        if ($scope.oldPrints[i].shipping_corp == $scope.dfExpress.shipping_corp) {
                            if ($scope.oldPrints[i].default_express) {
                                var isupdata = {
                                    print_id: $scope.oldPrints[i].print_id,
                                    store_id: $rootScope.store_id,
                                };
                                console.error("isupdata", isupdata);
                                isupdata.default_express = 0;
                                $scope.saveData(isupdata, 1).then(function(re) {
                                    is = re;
                                });
                            }
                        }
                    }
                } else {
                    is = 1;
                }
                console.error(is);
                return is;
            }).then(function(is) {
                //设置默认物流
                _.map($scope.oldPrints, function(da, ke) {
                    if (da.shipping_corp == code && da.default_template) {
                        var isupdata = {
                            print_id: da.print_id,
                            store_id: $rootScope.store_id,
                        };
                        console.error("isupdata", isupdata);
                        isupdata.default_express = 1;
                        $scope.saveData(isupdata)
                    }
                });
            });
        }

        //删除模板
        $scope.deleteTmp = function(id, $event) {
            if (id) {
                helper.myConfirm("确认删除吗？", function() {
                    dataService.printSellerDelete({ 'print_id': id }).then(function(result) {
                        if (!result.Msg) {
                            helper.myTip("success", $event.currentTarget, null, 6);
                            $scope.getlist();
                        } else {
                            helper.myTip("error", $event.currentTarget);
                        }
                    })
                });

            }
        }

        $scope.tmplatebindingAction = function() {
            $scope.printer_uuid = $location.search().printer_uuid;
            $scope.type_id = $scope.tep_type = 2;
            $scope.chosedType = "xiaopao";
            console.error($scope.chosedType);
            dataService.printrelationGet({
                'store_id': $rootScope.store_id,
                'printer_uuid': $scope.printer_uuid,
            }).then(function(result) {
                if (result) {
                    $scope.relations = result.relation_list;
                }
            })
        }
        //添加关联 
        $scope.addrelation = function(print_id) {
            dataService.printrelationAdd({
                'store_id': $rootScope.store_id,
                'printer_uuid': $scope.printer_uuid,
                'template_id': print_id,
            }).then(function(result) {
                $scope.tmplatebindingAction();
            })
        }
        //删除关联
        $scope.delrelation = function(id, $event) {
            if (id) {
                helper.myConfirm("确认删除吗？", function() {
                    dataService.printrelationDel({ 'relation_id': id }).then(function(result) {
                        if (!result.Msg) {
                            helper.myTip("success", $event.currentTarget, null, 6);
                            $scope.tmplatebindingAction();
                        } else {
                            helper.myTip("error", $event.currentTarget);
                        }
                    })
                });

            }
        }

        $scope.appZip = function() {
            $scope.appimg = 'https://qr.api.cli.im/qr?data=https%253A%252F%252Fmall.dhfapp.com%252Fweb%252Fsoft%252Fdhfprinter.apk&level=H&transparent=0&bgcolor=%23FFFFFF&forecolor=&blockpixel=12&marginblock=2&logourl=&size=400&text=&logoshape=no&fontsize=30&fontfamily=msyh.ttf&fontcolor=&incolor=&outcolor=&qrcode_eyes=&background=images%2Fbackground%2Fbg12.png&wper=0.74&hper=0.74&tper=0.13&lper=0.13&eye_use_fore=1&qrpad=10&kid=bizcliim&time=1544504181&key=d1acfd1fdd5cba8d0a82657f71a8de28';
            $scope.loginWin = $.alert({
                backdrop: "static",
                keyboard: false,
                // bgcolor: "rgb(0,0,0,0.9)",
                title: '<span >扫描下载打印app</span>',
                body: '<div style="text-align: center;"> <div><img ng-src="{{appimg}}"></div>',
                okBtn: '{{"login"|translate}}',
                closeBtn: true,
                hasfoot: false,
                transition: true,
                width: 'small',
                show: function(e) {
                    $compile($(e.currentTarget).contents())($scope);
                },
                okHide: function(e) {

                },
            });
            // 
        }
    }
})();